

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service

import undetected_chromedriver as uc


chromedriverPath = "../dev/chrome/chromedriver.exe"

driver_list = []


# 配置chrome驱动
def loadChromeDriver():
    print("配置浏览器驱动")
    chromePath = "../dev/chrome/chrome.exe"
    chromedriverPath = "../dev/chrome/chromedriver.exe"

    chrome_location = chromePath
    # os.chmod(chrome_location, 0o777)
    ser = Service()
    ser.path = chromedriverPath
    # 谷歌浏览器驱动地址
    options = Options()
    options.binary_location = chrome_location
    options.add_experimental_option('excludeSwitches', ['enable-automation'])
    options.add_argument('--window-size=1050,800')
    #options.add_argument('--incognito')
    options.add_argument("--disable-cache")
    options.add_argument('--disable-infobars')
    options.add_argument('--log-level=3')
    options.add_argument('--no-sandbox')
    # options.add_argument("--headless")
    options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36')
    options.add_experimental_option('excludeSwitches', ['enable-automation'])

    options.add_argument('--disable-blink-features=AutomationControlled')
    options.add_argument("--disable-blink-features")
    options.add_argument("--load-extension=../chrome-plugin/replace-js")  # chrome插件目录 替换js

    options.ignore_local_proxy_environment_variables()
    driver = webdriver.Chrome(options=options, service=ser)

    # with open('./dev/js/stealth.min.js') as f:
    #     js = f.read()

    # driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
    #     "source": js
    # })

    return driver



def loadChromeDriverControl():
    print("loadChromeDriverControl....")
    options = Options()
    options.add_experimental_option("debuggerAddress", "127.0.0.1:9527")
    # options.add_argument("--remote-debugging-port=9527")

    ser = Service()
    ser.path = chromedriverPath

    driver = webdriver.Chrome(options=options, service=ser)

    print("loadChromeDriverControl     driver....")
    return driver


def open_chrome_dr():
    chromePath = "../../dev/chrome/chrome.exe"
    chromedriverPath = "../../dev/chrome/chromedriver.exe"

    options = uc.ChromeOptions()

    # prefs = {"profile.managed_default_content_settings.images": 2}
    # options.add_experimental_option("prefs", prefs)

    driver = uc.Chrome(
        options=options,
        driver_executable_path=chromedriverPath,
        browser_executable_path=chromePath
    )

    return driver

